import { Avatar, Button, message, Modal } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import styles from '../index.module.scss'
import Null from './Null'
import { getConcer, getFans, updateFans } from '@/common/api'
import { getLs } from '@/common/common'
import { UserOutlined } from '@ant-design/icons';
// 粉丝页面
export default function Fans(props) {
  const { fansShow = false,type,updateFansShow,setUserInfo,Id,isUser=false} = props
  const [loading,setLoading] = useState(false)
  const [btnLoading,setBtnLoading] = useState(false)
  const [list, setList] = useState([]);
  const [hasMore, setHasMore] = useState(true); // 控制是否还有更多数据
  const observer = useRef()
  const [page, setPage] = useState(1);
  // 没有粉丝
  const [notPeople,setNotPeople]=useState(false)
  useEffect(() => {
    if (fansShow) {
      fetchItems()
    }
  }, [fansShow, page])
  // 调用列表接口
  const fetchItems = async () => {
    if (hasMore) {
      // 如果正在加载或没有更多数据，则不发起请求
      setLoading(true)
      let RES
      type === 'fansShow'?  RES = await getFans({ page, Id }):RES = await getConcer({ page, Id })
      setLoading(false)
      if(RES.data.data?.length===0){
        setHasMore(false)//如果没有数据，停止请求
        if(page===1){
          setNotPeople(true)
        }
      }else{
       setList(pre=>([...pre,...RES.data.data]))
      }
    }; 
  };
  const lastItemRef = (node) => {
    if(loading || !hasMore) return
    if (observer.current)  observer.current.disconnect();// 断开之前的观察
    observer.current = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      setPage((prevPage) => prevPage + 1);
    }
    },{
      root: null,        // 默认监视视口（可指定父级容器）
      threshold: 1.0     // 目标元素完全进入视口时才触发
    });
    if (node) observer.current.observe(node);
  };
  const closeModal = () => {
    setHasMore(true)
    setList([])
    setPage(1)
    observer.current = null
    setNotPeople(false)
    updateFansShow()
  }
  useEffect(()=>{console.log(list);},[list])
  // 关注取关
  const FollowAndUnblock = async(item)=>{
    const timer = Math.floor(Date.now() / 1000)
        const data={
            otherId:item._id,
            userId:Id,
            timer,
            type:item.isAttention
        }
    try {
            setBtnLoading(true)
            const RES = await updateFans(data)
            setBtnLoading(false)
            if(RES.code===200){
              setList(pre=>{
                return pre.map(ele=>{
                  if(ele._id===item._id){
                    return {
                      ...ele,
                      isAttention:!item.isAttention
                    }
                  }
                  return ele
                })
              })
              setUserInfo(pre=>({...pre,attentionNumber:item.isAttention?pre.attentionNumber-1:pre.attentionNumber+1}))
              // 更改用户粉丝关注数量
              // setAttention(RES.data.payFor)
              // 发送socket
             
                message.success(RES.data.msg)
            }
        } catch (error) {
            return error
        }
  }
  return (
    <>
      <Modal
        open={fansShow}
        onCancel={closeModal}
        footer={null}
        className={styles.Modal}
        width={350}
        // 右上角关闭按钮
        closable={false}
      >
        <ul>
          {list.map((item, index) => {
              return <li ref={list.length === index + 1?lastItemRef:null} key={item?._id}>
              { Boolean(item?.avator)?<Avatar src={`http://localhost:5000${item?.avator}`}/>:<Avatar icon={<UserOutlined />}/>}
                <span className={styles.name} >{item?.name}</span>
                {
                 isUser&&(item?.isAttention?<Button loading={btnLoading} onClick={()=>FollowAndUnblock(item)}>已关注</Button>:<Button loading={btnLoading} onClick={()=>FollowAndUnblock(item)} style={{backgroundColor:"red"}} type='primary'>回关</Button>)
                }
              </li>
          })}
          {
            page===1&&notPeople&&<Null text={type==='fans'?"粉丝":"关注"}/>
          }
          <p>{loading&&'loading......'}</p>
        </ul>
      </Modal>
    </>
  )
}
